package 极客时间.concurrence.并发编程实战篇.手写一把lock;

import java.util.Iterator;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicReference;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.LockSupport;

/**
 * @Author idea
 * @Date created in 10:03 下午 2020/7/22
 */
public class IdeaLockV1 implements Lock {

    /**
     * 占有资源的独有者
     */
    volatile AtomicReference<Thread> owner = new AtomicReference<>();

    /**
     * 等待锁资源的线程
     */
    volatile LinkedBlockingQueue<Thread> awiter = new LinkedBlockingQueue<>();

    @Override
    public void lock() {
        if(this.tryLock()){
            awiter.add(Thread.currentThread());
            //线程等待
            LockSupport.park();
            //对应unlock操作
            awiter.remove(Thread.currentThread());
        }
    }

    @Override
    public void lockInterruptibly() throws InterruptedException {

    }

    @Override
    public boolean tryLock() {
        //CAS,比较和设置
        if (owner.compareAndSet(null, Thread.currentThread())) {
            return true;
        }
        return false;
    }

    @Override
    public boolean tryLock(long time, TimeUnit unit) throws InterruptedException {
        return false;
    }



    @Override
    public void unlock() {
        if (owner.compareAndSet(Thread.currentThread(), null)) {
            Iterator<Thread> iterator = awiter.iterator();
            while (iterator.hasNext()) {
                Thread next = iterator.next();
                if (null != next) {
                    //这个时候就会影响到lock操作那边到程序
                    LockSupport.unpark(next);
                }
            }
        }
    }

    @Override
    public Condition newCondition() {
        return null;
    }
}
